package com.sghy.xcxservice.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@ControllerAdvice //全局捕获控制器（@Controller）中抛出的异常（配合 @ExceptionHandler 使用）
public class GlobalExceptionHandler {
    
    private HttpHeaders getCorsHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*"); // 替换为前端的域名
        headers.add("Access-Control-Allow-Credentials", "false");
        headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        headers.add("Access-Control-Allow-Headers", "*");
        return headers;
    }
    
    // 捕获所有校验失败的异常
    @ExceptionHandler(BindException.class)
    public ResponseEntity<?> handleValidationExceptions(BindException ex) {
        FieldError error = ex.getBindingResult().getFieldErrors().get(0);
        String errorMessage = error.getDefaultMessage();  // 获取错误提示信息
        return ResponseEntity.status(HttpStatus.OK).body(new ErrorResponse(2002, errorMessage));
        
    }
    /*
    自定义错误
     */
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<?> handleCustomException(CustomException ex) {
        Error errorCode = ex.getError();// 提取自定义异常中的错误码
        return ResponseEntity.status(HttpStatus.OK)// 使用自定义状态码
                .body(new ErrorResponse(errorCode.getCode(), ex.getMessage()));// 返回详细业务信息
    }
    
    /**
     * 请求方式错误get or post
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<ErrorResponse> handleNullPointerException(HttpRequestMethodNotSupportedException ex) {
        // 返回详细的错误信息
        return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)
                .body(new ErrorResponse(405,"请求类型错误:不支持"+ex.getMethod()+"请求"));
    }
    
    /**
     * 捕获全局的配置@RequestParam中缺失的参数
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<ErrorResponse> handleNullRequestParameterException(MissingServletRequestParameterException ex) {
        // 返回详细的错误信息
        return ResponseEntity.status(HttpStatus.OK).body(new ErrorResponse(2002,
                ex.getParameterName()+"参数缺失"));
    }
    
    /**
     * 上传文件过大超过服务器设置异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<ErrorResponse> handleNullPointerException(MaxUploadSizeExceededException ex) {
        // 返回详细的错误信息
        return ResponseEntity.status(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE)
                .body(new ErrorResponse(413,"上传文件超出服务器规定大小"));
    }
    
    //    /**
    //     * 空指针异常处理
    //     * @param ex
    //     * @return
    //     */
        @ExceptionHandler(NullPointerException.class)
        public ResponseEntity<ErrorResponse> handleNullPointerException(HttpServletRequest request, NullPointerException ex) {
            // 打印错误信息
            String ID = String.valueOf(System.currentTimeMillis())+ (int) (Math.random() * 900000 + 100000);
            logger.error("服务器异常,异常ID:"+ ID + " URL:"+request.getRequestURI(), ex);
            // 获取请求的URL和请求参数
            Map<String, String[]> paramMap = request.getParameterMap();
            for (String key : paramMap.keySet()) {
                String[] values = paramMap.get(key);
                for (String value : values) {
                    logger.info(key + ": " + value);
                }
            }
            // 返回通用的错误响应
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ErrorResponse(500, "空指针异常,请联系系统管理员,异常ID:"+ID));
        }
    
    
    /*用于捕获所有未被其他 @ExceptionHandler 捕获的异常（包括系统异常、运行时异常等）*/
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(Exception.class)  // 统一处理所有未捕获的异常
    public ResponseEntity<?> handleGeneralException(HttpServletRequest request, Exception ex) {
        // 打印错误信息
        String ID = String.valueOf(System.currentTimeMillis())+ (int) (Math.random() * 900000 + 100000);
        logger.error("服务器异常,异常ID:"+ ID + " URL:"+request.getRequestURI(), ex);
        // 获取请求的URL和请求参数
        Map<String, String[]> paramMap = request.getParameterMap();
        for (String key : paramMap.keySet()) {
            String[] values = paramMap.get(key);
            for (String value : values) {
                logger.info(key + ": " + value);
            }
        }
        // 返回通用的错误响应
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ErrorResponse(500, "服务器异常,异常ID:"+ID));
    }
}
